package com.dailywork.basepro.compro;

import java.util.Arrays;

public class BitOper {
    public static void main(String[] args) {
        bitOper(5);
        bitSet(5, 5);
        countOneBit(5);
        is2Exp(5);
        countBits(7);
    }

    private static void bitOper(int value) {
        if ((value & 1) == 0) {
            System.out.println("偶数");
        } else {
            System.out.println("奇数");
        }
    }

    private static void bitSet(int value, int n) {
        // 设置第N位为1
        System.out.println(value | (1 << n));
        // 设置第N位为0
        System.out.println(value & ~(1 << n));
        // 将第N位的值取反
        System.out.println(value ^ (1 << n));
        // 将最右边的1设置为0
        System.out.println(value & (value - 1));
    }

    private static void countOneBit(int value) {
        int count = 0;
        while (value != 0) {
            value = value & (value - 1);
            count++;
        }
        System.out.println("1 count is: " + count);
    }

    private static void is2Exp(int value) {
        if ((value & (value - 1)) == 0) {
            System.out.printf("%d不是2的幂次方！", value);
        } else {
            System.out.printf("%d是2的幂次方！", value);
        }
    }

    private static void countBits(int num) {
        int[] bits = new int[num + 1];
        for (int i = 1; i <= num; i++) {
            bits[i] = bits[i & (i - 1)] + 1;
        }
        System.out.println(Arrays.toString(bits));
    }
}
